package com.heima.app.gateway.filter;

import com.heima.app.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-09-12 14:07
 */
//编写全局过滤器中
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //1.判断是否需要鉴权  获取URI之后内容中会编码，getPath解码
        if(request.getURI().getPath().contains("login_auth")){
            //转发给下一个过滤器
            return chain.filter(exchange);
        }

        //2.获取token
        String token = request.getHeaders().getFirst("token");
        //3.判断token是否存在
        if(StringUtils.isBlank(token)){
            //设置为401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        try{
            //4.校验token是否有效
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            if(claimsBody == null){
                //token解析有问题
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
            //标注一下这段代码目前校验不是很有意义
            int result = AppJwtUtil.verifyToken(claimsBody);
            if(result == 1 || result == 2){
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }

            //解析出用户id 转发到后续微服务中
            //获取用户id
            Long id = claimsBody.get("id", Long.class);
            //将id传入微服务  把用户id设置到了请求头中
            ServerHttpRequest newRequest = request.mutate().header("userId", String.valueOf(id)).build();
            exchange.mutate().request(newRequest);

        }catch (Exception e){
            //TOken被篡改
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        return chain.filter(exchange);
    }

    //过滤器排序，值约小，优先级就越高
    @Override
    public int getOrder() {
        return 0;
    }
}
